<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/24/024
 * Time: 20:37
 */

namespace app\admin\model;

use think\Db;
use think\facade\Session;

class Single extends \think\Model
{
    protected $table = 'sy_tk_single';

    /**
     * 获取单条
     * @param $id
     * @return array|null|\PDOStatement|string|\think\Model
     */
    public function _findOne($id){
        return $this->where([['id', '=', $id]])->find();
    }

    
    /**
    * 通过名称获取信息
    */
    public function _findByName($name){
        return $this->where([['chapter_title', '=', $name]])->find();
    }
    
    //校验用户名是否存在
    public function _checkName($value){
        $data = $this->where([['chapter_title', '=', $value]])->find();
        if(!empty($data)){
            $this->error = '已存在';
            return false;
        }
        return true;
    }
    

    /**
    * 校验是否被冻结
    */
    public function _checkStatus($id){
        $data = $this->where(array('id'=>$id, 'status'=>1))->find();
        if(empty($data)){
            $this->error = '已禁用';
            return false;
        }
        return true;
    }

    /**
     * 章节列表
     * @param array $condition
     * @param int $page_size
     * @param string $order_by
     * @return \think\Paginator
     */
    public function _list($condition = [], $page_size = 20, $order_by = 'sort asc'){
        $obj = $this->alias('u')
            ->field('u.*,dd.detail_title,cc.chapter_title')
            ->join('sy_tk_chapter_detail dd', 'dd.id = u.detail_id', 'LEFT')
            ->join('sy_tk_chapters cc', 'cc.id = u.chapter_cate', 'LEFT')
            ->order('u.id desc')
            ->where('u.chapter_cate','gt',0);
        $result = get_page($obj, $condition, $page_size);

        $result0 = $result['list']->all();
        foreach ($result0 as $k=>$v){
            $cate_title_info     = Question::get($v['cate']);
            $v['cate_title']    = $cate_title_info['cate_title'];
            $v['q_title']       = mb_substr($v['q_title'],0,20).'...';
            $result['list'][$k] = $v;
        }
       
        return $result;
    }

    /**
     * 真题列表
     * @param array $condition
     * @param int $page_size
     * @param string $order_by
     * @return \think\Paginator
     */
    public function _list_two($condition = [], $page_size = 20, $order_by = 'sort asc'){
        $obj = $this->alias('u')
            ->field('u.*,dd.detail_title,cc.chapter_title')
            ->join('sy_tk_chapter_detail dd', 'dd.id = u.detail_id', 'LEFT')
            ->join('sy_tk_chapters cc', 'cc.id = u.chapter_cate', 'LEFT')
            ->order('u.id desc')
            ->where('u.chapter_cate','eq',0);
        $result = get_page($obj, $condition, $page_size);

        $result0 = $result['list']->all();
        foreach ($result0 as $k=>$v){
            $cate_title_info     = Question::get($v['cate']);
            $v['cate_title']    = $cate_title_info['cate_title'];
            $v['q_title']       = mb_substr($v['q_title'],0,20).'...';
            $result['list'][$k] = $v;
        }

        return $result;
    }

    /**
     * 添加
     * @param $post
     * @return bool
     */
    public function _create($post){
        $insert = [
            'chapter_title' => $post['chapter_title'],
            'cate' => $post['cate'],
            'create_at' => time(),

        ];
        if(!$this->insert($insert)){
            $this->error = '操作失败';
            return false;
        }
        return true;
    }


    /**
     * 删除
     * @param $id
     * @return bool
     */
    public function _remove($id){
        $result = $this->_findOne($id);
        if(!$result){
            $this->error = '无此';
            return false;
        }
        if(!$result->delete()){
            $this->error = '操作失败';
            return false;
        }
        
        return true;
    }

    /**
     * 批量删除
     * @param $id
     * @return bool
     */
    public function _removeAll($id){
        $ret = $this->where([['id', 'in', $id]])->delete();
        if(!$ret){
            $this->error = '操作失败';
            return false;
        }
        
        return true;
    }


    /**
     * 详情
     * @param $id
     * @return array|bool
     */
    public function _detail($id){
        $result = $this->_findOne($id)->toArray();
        if(!$result){
            $this->error = '无此数据';
            return false;
        }
        return $result;
    }


    /**
     * 修改
     * @param $post
     * @return bool
     */
    public function _modify($post){
        $result = $this->_findOne($post['id']);
        if(empty($result)){
            $this->error = '不存在';
            return false;
        }
        if(isset($post['q_title'])) $result->q_title = trim($post['q_title']);
        if(isset($post['q_a'])) $result->q_a = trim($post['q_a']);
        if(isset($post['q_b'])) $result->q_b = trim($post['q_b']);
        if(isset($post['q_c'])) $result->q_c = trim($post['q_c']);
        if(isset($post['q_d'])) $result->q_d = trim($post['q_d']);
        if(isset($post['q_e'])) $result->q_e = trim($post['q_e']);
        if(isset($post['q_site'])) $result->q_site = trim($post['q_site']);
        if(isset($post['q_answer'])) $result->q_answer = trim($post['q_answer']);
        if(isset($post['q_analysis'])) $result->q_analysis = trim($post['q_analysis']);
        if(isset($post['q_score'])) $result->q_score = trim($post['q_score']);
        if(isset($post['q_origin'])) $result->q_origin = trim($post['q_origin']);
        if($result->save() === false){
            $this->error = '操作失败';
            return false;
        }
        
        
        return true;
    }

    /**
    * 设置状态
    */
    public function _setStatus($request){
        $ff = $request['ff'];
        $id = $request['id'];
        if($ff == 1){
            $success = "停用成功";
            $error = "停用失败";
        }elseif($ff == -1){
            $success = "启用成功";
            $error = "启用失败";
        }
        
        
        $where = array('id'=>$id,'status'=>$ff);

        $data = $this->where($where)->find();
        if(empty($data)){
            $this->error = '该数据状态已改变';
            
            return false;
        }
        $data->status = -$ff;
        $ret = $data->save();
        if(!$ret){
            $this->error = $error;
            return false;
        }
        
        
        return true;
    }
    

    /**
    * 数据总条数
    */
    public function _count($where = []){
        return $this->alias('u')->where($where)->where('u.chapter_cate','gt',0)->count();
    }

    /**
     * 数据总条数
     */
    public function _count_two($where = []){
        return $this->alias('u')->where($where)->where('u.chapter_cate','eq',0)->count();
    }

    /**
    * 获取条件
    */
    public function _where($request){
        $p = isset($request['page']) ? $request['page'] : 1;
        $start = isset($request['start']) ? $request['start'] : '';
        $end = isset($request['end']) ? $request['end'] : '';
        $detail_id = isset($request['detail_id']) ? $request['detail_id'] : '';
        $q_title = isset($request['q_title']) ? $request['q_title'] : '';
        $cate = isset($request['cate']) ? $request['cate'] : '';
        
        $request['page'] = $p;
        $request['start'] = $start;
        $request['end'] = $end;
        $request['q_title'] = $q_title;
        $request['detail_id'] = $detail_id;
        $request['cate'] = $cate;
        
        $search = $request;
        
        $q_title = htmlspecialchars(addslashes(str_replace(' ', '', $request['q_title'])));
        $request['q_title'] = str_replace('%', "\%", $q_title);
        
        $tmp = $request;
        foreach($tmp as $k=>$v){
            if(empty($v)){
                unset($tmp[$k]);
            }
        }
        
        $where = '';
        foreach($tmp as $k=>$v){
            if($k == 'start'){
                $start = strtotime($v);
                $where .= "created >= $start and ";
            }elseif($k == 'end'){
                $end = strtotime($v) + 24*3600;
                $where .= "created <= $end and ";
            }elseif($k == 'q_title'){
                $where .= "u.q_title like '%$v%' and ";
            }elseif($k == 'detail_id'){
                $where .= "u.detail_id = $v and ";
            }elseif($k == 'cate'){
                $where .= "u.cate = $v and ";
            }
        }
        if(!empty($where)){
            $where = substr($where, 0, -4);
        }
        return array('search'=>$search,'where'=>$where);
    }

    /**
     * 添加答题记录
     */
    public function _add_wrong($mid,$vv,$request){
        $maps0['uid']       = $mid;
        $maps0['single_id'] = $vv['single_id'];
        $wrong_info = Db::name('tk_wrong')->where($maps0)->find();
        if($wrong_info){
            $ups0['wrong_answer'] = $vv['answer'];
            $ups0['create_at']     = time();
            Db::name('tk_wrong')->where($maps0)->update($ups0);
        }else{
            $insert0['single_id']    = $vv['single_id'];
            $insert0['detail_id']    = $request['detail_id'];
            $insert0['uid']          = $mid;
            $insert0['wrong_answer'] = $vv['answer'];
            $insert0['chapter_type'] = $request['chapter_type'];
            $insert0['create_at']    = time();
            Db::name('tk_wrong')->where($maps0)->insert($insert0);
        }
    }

    /**
     * 添加答题记录
     */
    public function _add_record($mid,$request,$back_data){
        $map['uid']       = $mid;
        $map['detail_id'] = $request['detail_id'];
        $is_commit = Db::name('tk_record')->where($map)->find();
        $back_id   = $is_commit['id'];
        if($is_commit){
            $ups['content']   = $request['content'];
            $ups['create_at'] = time();
            $result           =  Db::name('tk_record')->where($map)->update($ups);
        }else{
            $insert['uid']       = $mid;
            $insert['total_number']  = $back_data['total_number'];
            $insert['right_number']  = $back_data['right_number'];
            $insert['wrong_number']  = $back_data['wrong_number'];
            $insert['total_score']   = $back_data['total_score'];
            $insert['use_time']      = $request['use_time'];
            $insert['detail_id']     = $request['detail_id'];
            $insert['content']       = $request['content'];
            $insert['chapter_type']  = $request['chapter_type'];
            $insert['create_at']     = time();
            $back_id                 =  Db::name('tk_record')->insertGetId($insert);
        }
        return $back_id;
    }

    /**
     * 全站最高分
     */
    public function _max_score($detail_id){
        $max_score = Db::name('tk_record')->where('detail_id',$detail_id)->max('total_score');
        if(!$max_score){
            $max_score = 0;
        }
        return $max_score;
    }

    /**
     * 我的排名
     */
    public function _rank_number($score,$detail_id){

        $record_arr = Db::name('tk_record')->where('detail_id',$detail_id)->column('total_score');
        $high       = [];
        foreach ($record_arr as $k=>$v){
            if($v>=$score){
                $high[] = $score;
            }
        }
        $fenzi = count($high);
        $fenmu = count($record_arr);
        $back = $fenzi.'/'.$fenmu;
        return $back;


    }

    /**
     * 遍历获取我的答案
     */
    public function get_my_answer($content_arr,$id){
        $my_answer = "";
        foreach ($content_arr as $k=>$v){
            if($id==$v['single_id']){
                $my_answer = $v['answer'];
                break;
            }
        }
        return $my_answer;
    }

    /**
     * 获取错题数目
     */
    public function _get_wrong_number($uid,$chapter_type){
        $maps['uid']          = $uid;
        $maps['chapter_type'] = $chapter_type;
        $number = Db::name('tk_wrong')->where($maps)->count();
        return $number;
    }

}